package com.ctl.algorithm;


import java.util.concurrent.Exchanger;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: Test</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2019</p>
 * <p>Company: www.hanshow.com</p>
 *
 * @author ctl
 * @version 1.0
 * @date 2021-09-27 19:37
 */
public class FooBarTest {
    static Semaphore semaphore = new Semaphore(1);

    static class Bar implements Runnable {
        private int times;
        private Exchanger<String> exchanger;

        public Bar(int times, Exchanger exchanger) {
            this.times = times;
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int i = 0; i < times; i++) {
                try {
                    exchanger.exchange("");
                    try {
                        semaphore.acquire();
                    } catch (Exception e) {
                    }
                    System.out.println("bar");
                } catch (Exception e) {
                }
            }
        }
    }

    static class Foo implements Runnable {
        private int times;
        private Exchanger<String> exchanger;

        public Foo(int times, Exchanger exchanger) {
            this.times = times;
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int i = 0; i < times; i++) {
                try {
                    exchanger.exchange("");
                    System.out.print("foo");
                    semaphore.release();
                } catch (Exception e) {
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int times = 10;
        Exchanger<String> integerExchanger = new Exchanger<>();
        semaphore.acquire();
        new Thread(new Foo(times, integerExchanger)).start();
        new Thread(new Bar(times, integerExchanger)).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
        }
        System.out.println("##");
    }
}
